import 'reflect-metadata'
import { app, BrowserWindow } from 'electron'
import { Application } from './core/application'
import { ServiceLocator } from './core/container'

/**
 * 应用程序主入口点
 * 负责应用的启动和单实例控制
 */

let application: Application | null = null

/**
 * 启动应用程序
 */
async function startApplication(): Promise<void> {
  try {
    application = new Application()

    // 设置全局服务定位器
    ServiceLocator.setContainer(application.getContainer())

    // 初始化应用程序
    await application.initialize()

  } catch (error) {
    console.error('Failed to start application:', error)
    app.quit()
  }
}

/**
 * 关闭应用程序
 */
async function shutdownApplication(): Promise<void> {
  if (application) {
    await application.shutdown()
    application = null
  }
}

// 确保只有一个应用实例
const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  app.quit()
} else {
  // 处理第二个实例启动
  app.on('second-instance', () => {
    if (application) {
      const container = application.getContainer()
      if (container.has('mainWindow')) {
        const mainWindow = container.get<BrowserWindow>('mainWindow')
        if (mainWindow && !mainWindow.isDestroyed()) {
          if (mainWindow.isMinimized()) mainWindow.restore()
          mainWindow.focus()
        }
      }
    }
  })

  // 等待Electron准备就绪后启动应用
  app.whenReady().then(startApplication)

  // 应用即将退出时清理资源
  app.on('before-quit', shutdownApplication)
}
